﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;

namespace DailyBread.Helpers
{
    [DataContract()]
    public class BreadCache<TKey, TValue>
    {
        [DataMember]
        public readonly Dictionary<TKey, TValue> entries;
        [DataMember]
        private readonly int capacity;

        public BreadCache(int capacity = 16)
        {
            if (capacity <= 0)
                throw new ArgumentOutOfRangeException(
                    "capacity",
                    "Capacity should be greater than zero");
            this.capacity = capacity;
            entries = new Dictionary<TKey, TValue>();
        }

        public void Set(TKey key, TValue value)
        {
            TValue entry;
            if (!entries.TryGetValue(key, out entry))
            {
                if (entries.Count == capacity)
                {
                    // Acquire keys and sort them.
                    var list = entries.Keys.ToList();
                    list.Sort();
                    entries.Remove(list.First()); // remove the first one if we reach the capacity
                }
                entries.Add(key, value);
            }

            entry = value;
        }

        public bool TryGetValue(TKey key, out TValue value)
        {
            value = default(TValue);
            TValue entry;
            if (!entries.TryGetValue(key, out entry)) return false;
            value = entry;
            return true;
        }
    }

}
